package com.example.palyerdemo

import android.graphics.Paint
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.CheckBox
import android.widget.TextView
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView

/**
 * 片段列表适配器：承担“勾选=删除”交互，把变更回调到外部（如 SegmentedPlayer/MainActivity）。
 * 注意：
 * - 仅负责展示与交互，不在内部修改 [SegmentManager] 数据，避免多处状态源。
 */
class SegmentAdapter(
    private val onToggleDelete: (index: Int, deleted: Boolean) -> Unit
) : ListAdapter<Segment, SegmentAdapter.SegmentVH>(DiffCallback) {

    object DiffCallback : DiffUtil.ItemCallback<Segment>() {
        override fun areItemsTheSame(oldItem: Segment, newItem: Segment): Boolean = oldItem.index == newItem.index
        override fun areContentsTheSame(oldItem: Segment, newItem: Segment): Boolean =
            oldItem.startMs == newItem.startMs && oldItem.endMs == newItem.endMs && oldItem.deleted == newItem.deleted
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SegmentVH {
        val inflater = LayoutInflater.from(parent.context)
        val view = inflater.inflate(R.layout.item_segment, parent, false)
        return SegmentVH(view)
    }

    override fun onBindViewHolder(holder: SegmentVH, position: Int) {
        holder.bind(getItem(position), onToggleDelete)
    }

    class SegmentVH(itemView: View) : RecyclerView.ViewHolder(itemView) {
        private val tvTime: TextView = itemView.findViewById(R.id.tvSegTime)
        private val tvTitle: TextView = itemView.findViewById(R.id.tvSegTitle)
        private val cbDelete: CheckBox = itemView.findViewById(R.id.cbDelete)

        /** 绑定单个 item 的展示与交互。*/
        fun bind(segment: Segment, onToggle: (index: Int, deleted: Boolean) -> Unit) {
            tvTime.text = String.format("%s", formatSecond((segment.durationMs / 1000).toInt()))
            tvTitle.text = "段${segment.index + 1}"
            tvTitle.paintFlags = if (segment.deleted) {
                tvTitle.paintFlags or Paint.STRIKE_THRU_TEXT_FLAG
            } else {
                tvTitle.paintFlags and Paint.STRIKE_THRU_TEXT_FLAG.inv()
            }
            cbDelete.setOnCheckedChangeListener(null)
            cbDelete.isChecked = segment.deleted
            cbDelete.setOnCheckedChangeListener { _, isChecked ->
                onToggle(segment.index, isChecked)
            }
        }

        private fun formatSecond(totalSeconds: Int): String {
            val m = totalSeconds / 60
            val s = totalSeconds % 60
            return String.format("%02d:%02d", m, s)
        }
    }
}


